<template>
  <div id="userInfoPage">
    <a-card title="个人信息">
      <a-form 
        v-if="!isEditing" 
        :model="userInfo" 
        layout="vertical"
      >
        <a-form-item label="用户昵称">
          <div>{{ userInfo.userName || '未设置' }}</div>
        </a-form-item>
        
        <a-form-item label="用户头像">
          <a-avatar :size="64" :src="userInfo.userAvatar" />
        </a-form-item>
        
        <a-form-item label="用户简介">
          <div>{{ userInfo.userProfile || '未设置' }}</div>
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" @click="startEdit">编辑信息</a-button>
        </a-form-item>
      </a-form>
      
      <a-form 
        v-else
        :model="editForm" 
        layout="vertical"
        @finish="updateUserInfo"
      >
        <a-form-item label="用户昵称" name="userName">
          <a-input v-model:value="editForm.userName" />
        </a-form-item>
        
        <a-form-item label="用户头像" name="userAvatar">
          <a-upload
            name="file"
            :before-upload="beforeUpload"
            :customRequest="handleUpload"
            :show-upload-list="false"
            accept="image/*"
          >
            <a-avatar :size="64" :src="editForm.userAvatar" style="margin-right: 10px;" />
            <a-button>
              <upload-outlined></upload-outlined>
              点击上传
            </a-button>
          </a-upload>
          <div v-if="uploading" style="margin-top: 10px;">
            <a-spin />
            <span style="margin-left: 10px;">上传中...</span>
          </div>
        </a-form-item>
        
        <a-form-item label="用户简介" name="userProfile">
          <a-textarea v-model:value="editForm.userProfile" :rows="4" />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">保存</a-button>
            <a-button @click="cancelEdit">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { getLoginUserUsingGet, updateUserUsingPost } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import axios from 'axios'

// 添加图标导入
import { UploadOutlined } from '@ant-design/icons-vue'

const loginUserStore = useLoginUserStore()

// 用户信息
const userInfo = ref<API.LoginUserVO>({
  id: undefined,
  userName: undefined,
  userAvatar: undefined,
  userProfile: undefined,
  userRole: undefined,
})

// 编辑状态
const isEditing = ref(false)

// 添加上传状态
const uploading = ref(false)

// 编辑表单
const editForm = reactive<API.UserUpdateRequest>({
  id: undefined,
  userName: undefined,
  userAvatar: undefined,
  userProfile: undefined,
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0 && res.data.data) {
      userInfo.value = res.data.data
      // 更新全局状态
      loginUserStore.setLoginUser(res.data.data)
    } else {
      message.error('获取用户信息失败: ' + (res.data.message || '未知错误'))
    }
  } catch (e) {
    message.error('获取用户信息异常')
  }
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
  // 初始化表单数据
  editForm.id = userInfo.value.id
  editForm.userName = userInfo.value.userName
  editForm.userAvatar = userInfo.value.userAvatar
  editForm.userProfile = userInfo.value.userProfile
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
}

// 更新用户信息
const updateUserInfo = async () => {
  try {
    // 创建一个不包含 userAvatar 的对象用于更新用户信息
    const updateData = {
      id: editForm.id,
      userName: editForm.userName,
      userProfile: editForm.userProfile
    }
    
    const res = await updateUserUsingPost(updateData)
    if (res.data.code === 0) {
      message.success('更新成功')
      isEditing.value = false
      // 重新获取用户信息
      await fetchUserInfo()
    } else {
      message.error('更新失败: ' + (res.data.message || '未知错误'))
    }
  } catch (e) {
    message.error('更新异常')
  }
}

// 添加上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 添加处理上传逻辑
const handleUpload = async (options: any) => {
  const { file, onSuccess, onError } = options
  
  uploading.value = true
  
  try {
    // 创建 FormData 对象用于上传文件
    const formData = new FormData()
    formData.append('file', file)
    
    // 调用后端上传接口
    const response = await axios.post('/api/user/uploadHeadImage', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.code === 0) {
      // 上传成功，更新头像URL
      editForm.userAvatar = response.data.data
      onSuccess()
      message.success('上传成功')
    } else {
      onError()
      message.error('上传失败: ' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    onError()
    message.error('上传失败')
  } finally {
    uploading.value = false
  }
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
#userInfoPage {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
}

.ant-avatar {
  margin-bottom: 10px;
}
</style>

